// TelegramFetchService.java
package com.wangfugui.mybatisplus.cls;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
public class TelegramFetchService {

    @Autowired
    private TelegramDataService telegramDataService;
    
    @Autowired
    private RestTemplate restTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final String API_URL = "https://api.98dou.cn/api/hotlist/cls/all?apiKey=63c6be12ab4e20dae830f7e673f067c3";
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Scheduled(fixedRate = 5 * 60 * 1000) // 每10分钟执行一次
    public void fetchAndSaveTelegramData() {
        try {
            log.info("开始获取财联社电报数据: {}", LocalDateTime.now().format(TIME_FORMATTER));
            
            // 发送HTTP请求获取数据
            String jsonResponse = restTemplate.getForObject(API_URL, String.class);
            
            if (jsonResponse != null) {
                JsonNode rootNode = objectMapper.readTree(jsonResponse);
                boolean success = rootNode.path("success").asBoolean();
                
                if (success) {
                    JsonNode dataArray = rootNode.path("data");
                    if (dataArray.isArray()) {
                        int count = 0;
                        boolean hasExistingIdOriginal = false;

                        for (JsonNode itemNode : dataArray) {
                            // 检查 idOriginal 是否已存在
                            Long idOriginal = itemNode.path("id_original").asLong();
                            QueryWrapper<TelegramData> checkWrapper = new QueryWrapper<>();
                            checkWrapper.eq("id_original", idOriginal);

                            if (telegramDataService.count(checkWrapper) > 0) {
                                log.info("检测到已存在的 idOriginal: {}, 跳过此条数据", idOriginal);
                                break; // 跳过这条数据，但继续处理后续数据
                            }

                            // 保存新数据
                            TelegramData telegramData = parseTelegramData(itemNode);
                            telegramDataService.save(telegramData);
                            count++;
                        }


                        if (hasExistingIdOriginal) {
                            log.info("由于遇到已存在的 idOriginal，本次只处理了部分数据");
                        } else {
                            log.info("成功保存 {} 条电报数据", count);
                        }
                    }
                } else {
                    log.warn("API请求失败: {}", rootNode.path("msg").asText());
                }
            }
        } catch (Exception e) {
            log.error("获取或保存财联社电报数据时出错: ", e);
        }
    }

    private TelegramData parseTelegramData(JsonNode itemNode) {
        TelegramData telegramData = new TelegramData();
        telegramData.setTitle(itemNode.path("title").asText());
        telegramData.setContent(itemNode.path("content").asText());
        telegramData.setUrl(itemNode.path("url").asText());
        telegramData.setMobileUrl(itemNode.path("mobileUrl").asText());
        telegramData.setReadingNum(itemNode.path("reading_num").asInt());
        telegramData.setIdOriginal(itemNode.path("id_original").asLong());
        telegramData.setAudioUrl(itemNode.path("audio_url").asText());
        
        // 解析时间
        String timeStr = itemNode.path("time").asText();
        LocalDateTime publishTime = LocalDateTime.parse(timeStr, TIME_FORMATTER);
        telegramData.setPublishTime(publishTime);
        
        telegramData.setCreateTime(LocalDateTime.now());
        telegramData.setUpdateTime(LocalDateTime.now());
        
        return telegramData;
    }
}
